package arrays;

import interfaces.IArrayDequeue;

import java.util.ArrayList;
import java.util.Arrays;

import javax.management.ReflectionException;

import util.ReflectionUtility;

public class ArrayDequeue implements IArrayDequeue {

	public String[] a;

	/**
	 * The index of first element in array dequeue
	 */
	public int j;

	/**
	 * The number of elements in array
	 */
	public int n;

	public ArrayDequeue() {
		a = new String[0];
		j = 0;
		n = 0;
	}

	@Override
	public void add(int i, String x) {
		if (n + 1 > a.length)
			resize();
		if (i < n / 2) {
			j = j == 0 ? a.length - 1 : j - 1;
			for (int k = 0; k < i; k++) {
				a[(j + k) % a.length] = a[(j + k + 1) % a.length];
			}
		} else {
			for (int k = n; k > i; k--) {
				a[(j + k) % a.length] = a[(j + k - 1) % a.length];
			}
		}
		a[(j + i) % a.length] = x;
		n++;
	}

	@Override
	public String remove(int i) {

		String x = a[(j + i) % a.length];
		if (i < n / 2) {
			for (int k = i - 1; k > 0; k--) {
				a[(j + k) % a.length] = a[(j + k - 1) % a.length];
			}
			j = (j + 1) % a.length;
		} else {
			for (int k = i; k < n - 1; k++) {
				a[(j + k) % a.length] = a[(j + k + 1) % a.length];
			}
		}

		n--;
		if (3 * n < a.length) {
			resize();
		}
		return x;
	}
	
	public String get(int i){
		String x = a[(j + i) % a.length];
		return x;
	}
	public String set(int i, String x){
		String y = a[(j + i) % a.length];
		a[(j + i) % a.length]=x;
		return y;
	}
	@Override
	public void resize() {
		String[] b = new String[Math.max(1, 2 * n)];
		for (int k = 0; k < n; k++) {
			b[k] = a[(j + k) % a.length];

		}
		a = b;
		j = 0;

	}

	public String[] getA() {
		return a;
	}

	public int getJ() {
		return j;
	}

	public int getN() {
		return n;
	}
	public void add(String x){
		this.add(n, x);
	}
	public String remove(){
		return this.remove(0);
	}
	public int size(){
		return n;
	}


}
